<?php

if (!defined('SMF'))
	die('Hacking attempt...');

function snet_init($memID)
{
	global $context, $modSettings, $smcFunc, $user_profile, $sourcedir;

	// Since we're here, SN is obviosly running, so we won't need to check that. What we do need to check is wheather this user CAN have a wall at all.
	require_once($sourcedir . '/Subs-Members.php');
	if(in_array($memID,membersAllowedTo('snet_can_have_wall')))
	{
		// So, they *can* have a wall. Now, *do* they?
		if($modSettings['snet_enabled_for'] == 0)
			$enabled = true; // Enabled globally, and this user is allowed to have a wall.
		else
		{
			// Uh-oh, the users have been given free will. This will never end well, NEVER, I tell you! (well actually we just need a quick query, but I like being dramatic)
			$request = $smcFunc['db_query']('','
				SELECT enabled
				FROM {db_prefix}snet_users
				WHERE id_user = {int:user}
				LIMIT 1',
				array(
					'user' => $memID,
				)
			);
			
			// If the user hasn't choosen yet.
			if($smcFunc['db_num_rows']($request) == 0)
			{
				// It's on by default.
				if($modSettings['snet_enabled_for'] == 1)
					$enabled = true;
				// It's off by default.
				else
					$enabled = false;
			}
			// They're in the database, means they've made their choise.
			else
			{
				$row = $smcFunc['db_fetch_assoc']($request);
				$enabled = $row['enabled'] == 1 ? true : false;
			}
			
			// Fly, fly...
			$smcFunc['db_free_result']($request);
		}
	}
	else
		$enabled = false;
		
	// So it begins...
	if($enabled)
		simplenetwork($memID);
}

// The actual profile/wall.
function simplenetwork($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir, $embedder_check;
	
	// We'll need this, that's for sure.
	require_once($sourcedir . '/snet/Subs-SimpleNetwork.php');	
	
	loadTemplate('/snet/SimpleNetwork');
	loadLanguage('SimpleNetwork');
	
	// Make sure videos can be used (i.e and embedder is installed)
	$embedder_check = (file_exists($sourcedir . '/AutoEmbedMediaPro2.php') || (file_exists($sourcedir . '/Aeva-Subs.php') && $modSettings['aeva_enable'] == 1));
	
	// Figgure out what we're allowed to do here. This is a PITA.
	$context['can_comment'] = snet_allowed_to('comment',$memID);
	$context['can_like'] = snet_allowed_to('like',$memID);
	$context['can_dislike'] = snet_allowed_to('dislike',$memID);
	$context['can_post'] = snet_allowed_to('post',$memID);
	$context['can_delete'] = snet_allowed_to('delete',$memID);
	$context['can_edit_profile'] = $context['user']['is_owner'] ? (allowedTo('profile_extra_own') || allowedTo('profile_title_own')) : (allowedTo('profile_extra_any') || allowedTo('profile_title_any'));
	
	// Available types of status updates.
	$context['status_update_types'] = array();
	if(!empty($modSettings['snet_enable_text'])) $context['status_update_types'][1] = 'text';
	if(!empty($modSettings['snet_enable_photo'])) $context['status_update_types'][2] = 'photo';
	if(!empty($modSettings['snet_enable_link'])) $context['status_update_types'][3] = 'link';
	if(!empty($modSettings['snet_enable_quote'])) $context['status_update_types'][4] = 'quote';
	if(!empty($modSettings['snet_enable_video']) && $embedder_check)
		$context['status_update_types'][5] = 'video';
		
	// Figgure out which status type is the default one.
	$is_found = false;
	foreach(array_keys($context['status_update_types']) AS $type)
	{
		if(!$is_found)
			$context['default_type'] = $type;
		$is_found = true;
	}
	
	// What type of status are we dealing with now?
	$context['status_update_type'] = !empty($_REQUEST['status_type']) && in_array($_REQUEST['status_type'],array_keys($context['status_update_types'])) ? $_REQUEST['status_type'] : $context['default_type'];
	
	// If it's a photo we wanna know how they're gonna upload it.
	if(!empty($_REQUEST['photo_method']))
		$context['photo_method'] = $_REQUEST['photo_method'];
	else
		$context['photo_method'] = 2;
		
	$_REQUEST['status'] = empty($_REQUEST['status']) ? 0 : $_REQUEST['status'];
	
	if($_REQUEST['status'] != 0)
		snet_status_exists($_REQUEST['status'],$memID,true);
		
	// Always display stuff above and below, for the template.
	$context['template_layers'][] = 'simplenetwork';	

	$sub_actions = array(
		'main' => 'snet_main',
		'like' => 'snet_like',
		'dislike' => 'snet_dislike',
		'comment' => 'snet_comment',
		'post' => 'snet_post',
		'view' => 'snet_view',
		'delete' => 'snet_delete',
		'likecomment' => 'snet_likecomment',
		'dislikecomment' => 'snet_dislikecomment',	
		'deletecomment' => 'snet_deletecomment',		
	);
	
	$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($sub_actions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'main';
	
	// Go!
	$sub_actions[$_REQUEST['sa']]($memID);
	
	// This be magic.
	$context['html_headers'] = '
	<link rel="stylesheet" type="text/css" href="' . $settings['default_theme_url'] . '/css/simplenetwork.css" />  
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/snet/jquery.js"></script>
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/snet/encoder.js"></script>
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/snet/simplenetwork.js"></script>
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/snet/webcam/jquery.webcam.js"></script>
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/snet/jquery.elastic.js"></script>
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/snet/jquery.countdown.js"></script>
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/snet/jquery.charlimit.js"></script>';
}

// The main profile/wall
function snet_main($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	// Load all status updates!!! :D
	$context['status_updates'] = snet_load_status_updates($memID);	
	
	$event_start = !empty($_REQUEST['event_start']) ? $_REQUEST['event_start'] : 0;
	$context['wall_notes'] = snet_load_wall_events($memID,$event_start,10);
	$context['events_page_index'] = constructPageIndex($context['canonical_url'] . ';event_start=%1$d#event_log',$event_start, snet_count_wall_events($memID), 10, true);
	
	// Actually override the default profile and enter into the world of SimpleNetwork.
	$context['sub_template'] = 'snet_main';

}

// An individual status update
function snet_view($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;

	if(empty($_REQUEST['status']))
		redirectexit('action=profile;u=' . $memID);
	
	$context['status_update'] = snet_load_single_status_update($_REQUEST['status'],$memID);
	$context['comments'] = snet_load_comments($_REQUEST['status']);
	$context['num_comments'] = snet_count_comments($_REQUEST['status']);
	$context['sub_template'] = 'snet_view_status';	
}

// Like/Unlike a status update
function snet_like($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	if(empty($_REQUEST['status']) || empty($modSettings['snet_enable_like_buttons']))
		redirectexit('action=profile;u=' . $memID);
		
	snet_is_allowed_to('like',$memID);
	
	snet_like_status_update($_REQUEST['status'],$memID);
	
	if(isset($_REQUEST['backview']))
		redirectexit('action=profile;u=' . $memID . ';sa=view;status=' . $_REQUEST['status'] . '#status' . $_REQUEST['status']);
	else
		redirectexit('action=profile;u=' . $memID . '#status' . $_REQUEST['status']);
}

// Dislike/Un-dislike a status update
function snet_dislike($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	if(empty($_REQUEST['status']) || $modSettings['snet_enable_dislike_buttons'] == 0)
		redirectexit('action=profile;u=' . $memID);
		
	snet_is_allowed_to('dislike',$memID);	
	
	snet_dislike_status_update($_REQUEST['status'],$memID);
	
	if(isset($_REQUEST['backview']))
		redirectexit('action=profile;u=' . $memID . ';sa=view;status=' . $_REQUEST['status'] . '#status' . $_REQUEST['status']);
	else
		redirectexit('action=profile;u=' . $memID . '#status' . $_REQUEST['status']);
}

// Like/Unlike a comment
function snet_likecomment($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	if(empty($_REQUEST['comment']) || empty($modSettings['snet_enable_like_buttons']) || empty($modSettings['snet_enable_like_buttons_comments']))
		redirectexit('action=profile;u=' . $memID);
		
	snet_is_allowed_to('like',$memID);	
	
	snet_like_comment($_REQUEST['comment'],$memID);
	
	if(isset($_REQUEST['backview']))
		redirectexit('action=profile;u=' . $memID . ';sa=view;status=' . $_REQUEST['status'] . '#comment' . $_REQUEST['comment']);
	else
		redirectexit('action=profile;u=' . $memID . '#comment' . $_REQUEST['comment']);
}

// Dislike/Un-dislike a comment
function snet_dislikecomment($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	if(empty($_REQUEST['comment']) || $modSettings['snet_enable_dislike_buttons'] == 0 || empty($modSettings['snet_enable_dislike_buttons_comments']))
		redirectexit('action=profile;u=' . $memID);
		
	snet_is_allowed_to('dislike',$memID);	
	
	snet_dislike_comment($_REQUEST['comment'],$memID);
	
	if(isset($_REQUEST['backview']))
		redirectexit('action=profile;u=' . $memID . ';sa=view;status=' . $_REQUEST['status'] . '#comment' . $_REQUEST['comment']);
	else
		redirectexit('action=profile;u=' . $memID . '#comment' . $_REQUEST['comment']);
}

// Post a new status update
function snet_post($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir, $post_data;
	
	snet_is_allowed_to('post',$memID);
	
	require_once($sourcedir . '/snet/Subs-SimpleNetwork-Post.php');

	checkSession('post');

	// Go ahead and process this piece of junk.. Uh, did I say junk? I mean status update 0:)
	$post_data = array();
	snet_process_post($context['status_update_type'],$memID);
	
	if(!empty($context['snet_errors']))
		// An error occured, fall back to the main wall and let the user know.
		snet_main($memID);
	else
	{
		$new_status_id = snet_post_status_update($post_data,$memID);	
			
		// You're right, Sam, we brought the status update to the database. I am ready to go home.
		redirectexit('action=profile;u=' . $memID . '#status' . $smcFunc['db_insert_id']('{db_prefix}snet_status_updates', 'id_status'));
	}
	
}

// Post a new comment
function snet_comment($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	if(empty($_REQUEST['status']))
		redirectexit('action=profile;u=' . $memID);	
		
	snet_is_allowed_to('comment',$memID);	
	
	require_once($sourcedir . '/Subs-Editor.php');
	require_once($sourcedir . '/Subs-Post.php');
	require_once($sourcedir . '/snet/Subs-SimpleNetwork-Post.php');
	
	checkSession('post');
	
	$context['snet_comment_errors'] = array();
	
	$_POST['snet_comment'] = $_POST['snet_comment' . $_REQUEST['status']];
	
	// Check the content of the comment body.
	if (!isset($_POST['snet_comment']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['snet_comment']), ENT_QUOTES) === '')
	{
		$context['snet_comment_errors'][] = 'empty_comment';
		$_POST['snet_comment'] = '';
	}
	else
	{
		// More checkin'
		$_POST['snet_comment'] = $smcFunc['htmlspecialchars']($_POST['snet_comment'], ENT_QUOTES);
		preparsecode($_POST['snet_comment']);
		if ($smcFunc['htmltrim'](strip_tags(snet_format_text($_POST['snet_comment'], false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($_POST['snet_comment'], '[html]') === false))
			$context['snet_comment_errors'][] = 'empty_comment';
		elseif (!empty($modSettings['snet_max_comment_length']) && $smcFunc['strlen']($_POST['snet_comment']) > $modSettings['snet_max_comment_length'])
		{
			$context['snet_comment_errors'][] = 'long_comment';
			$txt['snet_error_long_comment'] = sprintf($txt['snet_error_long_comment'], $modSettings['snet_max_comment_length']);
		}
	}
	
	if(!empty($context['snet_comment_errors']))
	{
		// An error occured, fall back and let the user know.
		if(isset($_REQUEST['backview']))
			snet_view($memID);
		else
			snet_main($memID);
	}
	else
	{
		
		// Grab the ID of whoever posted this status update in the first place.
		$request = $smcFunc['db_query']('','
			SELECT id_user
			FROM {db_prefix}snet_status_updates
			WHERE id_status = {int:status}
			LIMIT 1',
			array(
				'status' => (int) $_REQUEST['status'],	
			)
		);
		list($status_owner) = $smcFunc['db_fetch_row']($request);
		$smcFunc['db_free_result']($request);	

		// Post a note to their wall!
		$id_note = snet_post_status_update(array(
			'body' => @serialize(array('body' => $status_owner != $memID ? 'snet_note_posted_comment_wall_post' : 'snet_note_posted_comment', 'note_type' => 'comment', 'replacements' => array('{user}' => $status_owner, '{username}' => 'snet_fetch_username(' . $status_owner . ');', '{status}' => $_REQUEST['status']), 'evalrepl' => array('{username}'))),
			'type' => 6,
		),$user_info['id'],false,true);
		
		// Just put it into the database already...
		$smcFunc['db_insert']('',
			'{db_prefix}snet_comments',
			array(
				'id_status' => 'int', 'id_user' => 'int', 'id_note' => 'int', 'date' => 'int', 'body' => 'string',
			),
			array(
				$_REQUEST['status'], $user_info['id'], $id_note, mktime(), $_POST['snet_comment'],
			),			
			array('id_comment')
		);			
		
		$id_comment = $smcFunc['db_insert_id']('{db_prefix}snet_comments', 'id_comment');
			
		// Redirect back.
		if(isset($_REQUEST['backview']))
			redirectexit('action=profile;u=' . $memID . ';sa=view;status=' . $_REQUEST['status'] . '#comment' . $id_comment);
		else
			redirectexit('action=profile;u=' . $memID . '#comment' . $id_comment);
	}
	
}

// Delete a status update
function snet_delete($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	if(empty($_REQUEST['status']))
		redirectexit('action=profile;u=' . $memID);
	
	snet_delete_status_update($_REQUEST['status'],$memID);
	
	redirectexit('action=profile;u=' . $memID);
}

// Delete a comment
function snet_deletecomment($memID)
{
	global $context, $txt, $user_info, $user_profile, $settings, $modSettings, $smcFunc, $sourcedir;
	
	if(empty($_REQUEST['comment']))
		redirectexit('action=profile;u=' . $memID);
	
	snet_delete_comment($_REQUEST['comment'],$memID);
	
	if(isset($_REQUEST['backview']))
		redirectexit('action=profile;u=' . $memID . ';sa=view;status=' . $_REQUEST['status']);
	else
		redirectexit('action=profile;u=' . $memID);
}


?>